package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author : Sonic
 * @version : 1.0
 * @createTime : 2024-12-22  14:54
 * @description : Redis实现全局唯一Id
 * 0--timeStamp--count
 */
@Component
public class RedisIDWorker {
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long end = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = end - BEGIN_TIMESTAMP;

        // 序列号
        // 获取日期精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 自增长
        // 将key对应的value自增1, 若键不存在, 则先将键的值初始化为0再自增1, 因此不会产生 空指针 问题
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 拼接并返回
        return timeStamp << 32 | count;
    }

    public static long getStartTime() {
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        return time.toEpochSecond(ZoneOffset.UTC);
    }
}
